#include "picturedao.h"
#include "picture.h"

#include <QSqlQuery>
#include <QStringList>
#include <QVariant>

PictureDao::PictureDao(QSqlDatabase &database) :
    m_database(database)
{

}

void PictureDao::init() const
{
    if( !m_database.tables().contains("pictures")) {
        QSqlQuery query(m_database);
        query.exec(QString("CREATE TABLE pictures")
                   + " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
                   + "album_id INTEGER, "
                   + "url TEXT)");
    }
}

void PictureDao::add_picture_in_album(int album_id, Picture &picture) const
{
    QSqlQuery query(m_database);
    query.prepare("INSERT INTO pictures (album_id, url) VALUES (:album_id, :url)");
    query.bindValue(":album_id", album_id);
    query.bindValue(":url", picture.file_url().toLocalFile());
    query.exec();

    picture.set_album_id(album_id);
    picture.set_id(query.lastInsertId().toInt());
}

void PictureDao::remove_picture(int id) const
{
    QSqlQuery query(m_database);
    query.prepare("DELETE FROM pictures WHERE id = :id");
    query.bindValue(":id", id);
    query.exec();
}

void PictureDao::remove_picture_for_album(int album_id) const
{
    QSqlQuery query(m_database);
    query.prepare("DELETE FROM pictures where album_id = :id");
    query.bindValue(":album_id", album_id);
    query.exec();
}

std::unique_ptr<std::vector<std::unique_ptr<Picture> > > PictureDao::pictures_for_album(int album_id) const
{
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM pictures WHERE album_id = :album_id");
    query.bindValue(":album_id", album_id);
    query.exec();

    auto list = std::make_unique<std::vector<std::unique_ptr<Picture>>>();
    while(query.next()) {
        auto picture = std::make_unique<Picture>(query.value("url").toString());
        picture->set_id(query.value("id").toInt());
        picture->set_album_id(query.value("album_id").toInt());

        list->push_back(move(picture));
    }
    return list;
}
